package com.lagou.edu.filter;

import com.lagou.edu.feign.UserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author 梅松
 * @Date 2021/10/23 12:33
 */
@Slf4j
@Component
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    UserFeign userFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        HttpCookie cookie = request.getCookies().getFirst("token");
        String path = request.getURI().getPath();

        if(path.startsWith("/api/user") || path.startsWith("/api/code")){
            //责任链继续，不校验
            return chain.filter(exchange);
        }
        //登录验证
        //验证不通过条件：1、cookie为null 2、cookie中没有token值 3、token值去反查email不存在
        if(cookie == null || StringUtils.isEmpty(cookie.getValue()) || StringUtils.isEmpty(userFeign.info(cookie.getValue()))
        ){
            //拒绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "token验证不通过";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));
            response.getHeaders().add("Access-Control-Allow-Origin","*");
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
